/*
 * TextMesureUtils.java
 * business
 *
 * Created by chentao on 2017/4/27.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.utils;

import android.graphics.Paint;
import android.graphics.Rect;

/**
 * 文本测量工具
 * <p>
 * Created by ChenTao(chentao7v@gmail.com) on 2017/4/27 0027 15:02
 */
public class TextMeasureUtils {

    /**
     * 获取文字的宽度
     */
    public static int getTextWidth(String text, Paint paint) {
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int width = bounds.left + bounds.width();
        return width;
    }

    /**
     * 获取文字的高度
     */
    public static int getTextHeight(String text, Paint paint) {
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int height = bounds.bottom + bounds.height();
        return height;
    }

    /**
     * 根据文本的长度自动截取文本,留下拼接"更多"的位置
     */
    public static String getCorrectText(String originText, String more, Paint textPaint, int widgetWidth) {

        int originTextWith = TextMeasureUtils.getTextWidth(originText, textPaint);
        int moreTextWidth = TextMeasureUtils.getTextWidth(more, textPaint);

        int correctLength = widgetWidth * 2 - moreTextWidth;
        if (originTextWith > correctLength) {
            int singleTextWidth = moreTextWidth / more.length();
            int index = correctLength / singleTextWidth;
            index -= 3;

            originText = originText.substring(0, index);
            return originText.concat("...");
        } else {
            return originText;
        }
    }

}
